<template>
  <div class="admin-profile-page">
    <el-card class="profile-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <h2>管理员个人资料</h2>
        </div>
      </template>

      <!-- 未登录或加载失败时显示 -->
      <div v-if="!isAuthenticated" class="error-message">
        <el-alert
          title="未登录或登录已过期"
          type="error"
          description="请重新登录后访问此页面"
          show-icon
          :closable="false"
        />
        <el-button type="primary" class="login-button" @click="handleRelogin">
          返回登录
        </el-button>
      </div>

      <!-- 已登录时显示表单 -->
      <el-form
        v-else
        ref="profileFormRef"
        :model="profileForm"
        :rules="rules"
        label-width="100px"
        class="profile-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="profileForm.username" disabled />
        </el-form-item>

        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="profileForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="profileForm.phone" placeholder="请输入手机号码" />
        </el-form-item>

        <el-form-item label="所属公司" prop="company">
          <el-input v-model="profileForm.company" disabled />
        </el-form-item>

        <el-form-item label="修改密码" prop="newPassword">
          <el-input
            v-model="profileForm.newPassword"
            type="password"
            placeholder="如需修改密码请输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="profileForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            保存修改
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getUserById, updateUser } from '@/apis/user'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()
const profileFormRef = ref(null)
const loading = ref(false)
const submitting = ref(false)

// 计算属性：检查是否已认证
const isAuthenticated = computed(() => {
  return userStore.isAuthenticated && userStore.user
})

const profileForm = ref({
  username: '',
  realName: '',
  phone: '',
  company: '本公司',
  newPassword: '',
  confirmPassword: ''
})

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback()
  } else if (value !== profileForm.value.newPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  newPassword: [
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validatePass, trigger: 'blur' }
  ]
}

const loadUserProfile = async () => {
  if (!isAuthenticated.value) {
    return
  }

  loading.value = true
  try {
    const userId = userStore.user.id
    const response = await getUserById(userId)
    if (response.code === 200) {
      const userData = response.data
      profileForm.value = {
        username: userData.username,
        realName: userData.realName,
        phone: userData.phone,
        company: userData.company || '本公司',
        newPassword: '',
        confirmPassword: ''
      }
    } else {
      ElMessage.error('获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息出错:', error)
    ElMessage.error('获取用户信息失败')
  } finally {
    loading.value = false
  }
}

const handleSubmit = async () => {
  if (!profileFormRef.value) return

  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const userId = userStore.user.id
        const updateData = {
          realName: profileForm.value.realName,
          phone: profileForm.value.phone
        }

        // 如果输入了新密码，则更新密码
        if (profileForm.value.newPassword) {
          updateData.password = profileForm.value.newPassword
        }

        const response = await updateUser(userId, updateData)
        if (response.code === 200) {
          ElMessage.success('更新成功')
          // 清空密码字段
          profileForm.value.newPassword = ''
          profileForm.value.confirmPassword = ''
        } else {
          ElMessage.error(response.msg || '更新失败')
        }
      } catch (error) {
        console.error('更新用户信息出错:', error)
        ElMessage.error('更新失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

const handleRelogin = () => {
  userStore.logout()
  router.push('/login')
}

onMounted(() => {
  loadUserProfile()
})
</script>

<style scoped>
.admin-profile-page {
  padding: 2rem;
  max-width: 800px;
  margin: 0 auto;
}

.profile-card {
  margin-top: 1rem;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-form {
  max-width: 500px;
  margin: 0 auto;
}

.error-message {
  text-align: center;
  padding: 2rem;
}

.login-button {
  margin-top: 1rem;
}

:deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: #f5f7fa;
}
</style>
